#region Header
//=============================================================================
//                          GShield (Game Shield)
//=============================================================================
//
// Original Programmer: Shawn Jackson
// Company: WaveTech Digital Technologies, Inc. (www.wtdt.com)
// Copyright: (c) 2006 WaveTech Digital Technologies, All Rights Reserved.
// Assembly: Engine
// Code File Name: UsageWatcher.cs
// Code File Date: 12/8/2006
//
// Code File Info: Usage Watcher System
//=============================================================================
/*
 * UPDATES
 * -------
 *    ShawnJ 5/5/2007 (0.9.0.x): Refactoring for OSS.
 *		0.9.6.x (ShawnJ) 12/24/2007: Moved from EntLib to Linq
 */
#endregion Header

#region License

/*
  GShield - Game Shield
  Copyright (C) 2006-2007 WaveTech Digital Technologies, Inc.
                                http://www.wtdt.com

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#endregion License

#region Includes

using System;
using System.Threading;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using WaveTech.GShield.Data;
using WaveTech.GShield.Data.Collections;
using WaveTech.GShield.Engine.Managers;
using WaveTech.GShield.Engine.Systems;
using WaveTech.GShield.Model;
using Exception=System.Exception;

#endregion

namespace WaveTech.GShield.Engine.Watchers
{
	/// <summary>
	/// Spawned System Watcher to Watch Game Usage
	/// </summary>
	public class UsageWatcher
	{
		private static Thread watcher;
		private static bool watcherActive;

		#region Constructor

		public UsageWatcher()
		{
			watcher = new Thread(Worker);
		}

		#endregion Constructor

		#region Start

		public void Start()
		{
			watcherActive = true;
			Logging.Write("The usage watcher system has been started.", LogCategory.Usage, LogPriority.Low,
			              LogType.UsageStartStop);

			if (watcher != null)
			{
				watcher.Start();
			}
			else
			{
				watcher = new Thread(Worker);
				watcher.Start();
			}
		}

		#endregion Start

		#region Stop

		public void Stop()
		{
			watcherActive = false;
			Logging.Write("The usage watcher system has been stopped.", LogCategory.Usage, LogPriority.Low,
			              LogType.UsageStartStop);

			if (watcher != null)
			{
				watcher.Abort();
				watcher = null;
			}
		}

		#endregion Stop

		#region Worker

		private void Worker()
		{
			try
			{
				Setting s = SettingsDAO.Get();

				while (watcherActive)
				{
					GameManager gm = GameManager.Instance;

					GameProcessCollection gameProcesses = ProcessHelper.Instance.GetAllGameProcesses();

					/*
					ProcessHelper pHelp = new ProcessHelper();

					GameProcessCollection gameProcesses = pHelp.GetDirectXProcesses();
					GameProcessCollection otherProcesses = pHelp.GetOtherProcesses();

					if (otherProcesses != null)
					{
						foreach (GameProcess process in otherProcesses)
						{
							if (gameProcesses == null)
								gameProcesses = new GameProcessCollection();

							gameProcesses.Add(process);
						}
					}
					*/

					if (gameProcesses != null && gameProcesses.Count > 0)
					{
						foreach (GameProcess p in gameProcesses)
						{
							Game g;
							g = gm.GetGame(p, p.FullPath, p.InternalName, p.ProductName, p.Company, p.Process.MainModule.FileName);

							UsagePolicy systemUsagePolicy = UsageDAO.GetUsagePolicyForSystem();
							UsagePolicy userUsagePolicy = UsageDAO.GetUsagePolicyForUser(ProcessHelper.Instance.GetOwnerForProcess(p.Id));

							UsagePolicy policy;

							if (userUsagePolicy == null)
							{
								policy = systemUsagePolicy;
							}
							else
							{
								policy = userUsagePolicy;
							}

							if (policy != null)
							{
								UsageLog l = UsageLogsDAO.GetUsageLogForProcessByDay(DateTime.Now,
								                                                     ProcessHelper.Instance.GetOwnerForProcess(p.Id), g.Id);

								if (l == null)
								{
									l = new UsageLog();
									l.Timestamp = DateTime.Now;
									l.Username = ProcessHelper.Instance.GetOwnerForProcess(p.Id);
									l.Type = (int) LogType.Usage;
								}

								TimeSpan time = DateTime.Now.Subtract(p.StartTime.Value);
								l.Time = time.Minutes;
								l.TimeType = (int) TimeType.Minutes;

								UsageLogsDAO.Save(l);

								int total = 0;
								UsageLogsCollection usageLogs = UsageLogsDAO.GetUsageLogsForUserByDay(DateTime.Now,
								                                                                      ProcessHelper.Instance.GetOwnerForProcess(
								                                                                      	p.Id));

								if (usageLogs != null)
									total = usageLogs.GetTotalPlayMinutes();

								if (
									UsageDAO.GetAllowedPlayingTimeForUser(ProcessHelper.Instance.GetOwnerForProcess(p.Id), DateTime.Now.DayOfWeek) !=
									null)
								{
									if (total >=
									    UsageDAO.GetAllowedPlayingTimeForUser(ProcessHelper.Instance.GetOwnerForProcess(p.Id),
									                                          DateTime.Now.DayOfWeek))
									{
										Logging.Write(
											"Worker: The total playing time for today, " + total + " minutes, has exceeded the limit, " +
											UsageDAO.GetAllowedPlayingTimeForUser(ProcessHelper.Instance.GetOwnerForProcess(p.Id), DateTime.Now.DayOfWeek) +
											" minutes. Killing the process.", LogCategory.Usage,
											LogPriority.Low, LogType.Usage, ProcessHelper.Instance.GetOwnerForProcess(p.Id));

										EmailManager.Instance.SendUsageViolationMessage(p.UserName, DateTime.Now, total);

										Messaging.ShowUsageWarning(total,
										                           UsageDAO.GetAllowedPlayingTimeForUser(
										                           	ProcessHelper.Instance.GetOwnerForProcess(p.Id), DateTime.Now.DayOfWeek).Value);

										ProcessHelper.Instance.KillProcess(p.Id);
									}
								}
							}
						}
					}

					if (s.UsageSleepTimer != null && int.Parse(s.UsageSleepTimer) > 0 && int.Parse(s.UsageSleepTimer) <= 3600000)
						Thread.Sleep(int.Parse(s.UsageSleepTimer));
					else
						Thread.Sleep(180000);
				}
			}
			catch (Exception e)
			{
				if (ExceptionPolicy.HandleException(e, "Engine Policy"))
					throw;
			}
		}

		#endregion Worker
	}
}